define(['jquery', 'layui', 'backend', 'table', 'form', 'jstree'], function ($, Layui, Backend, Table, Form, undefined) {
    var api = {
        "index": "/admin/sys/auth/group",
        "add": "/admin/sys/auth/group/add",
        "edit": "/admin/sys/auth/group/edit",
        "role": "/admin/sys/auth/group/role",
        "user": "/admin/sys/auth/group/user",
        "bindUser": '/admin/sys/auth/group/bind',
        "unbind": '/admin/sys/auth/group/unbind',
    }
    var Controller = {
        index: function () {
            // 渲染组别树
            Controller.api.renderLayTree();
            // 新增按钮
            $('#btn-add-group').on('click', function (e) {
                Mon.api.open(api.add, '新增角色组别', $(this).data() || {});
            })
            // 刷新
            $('#btn-refresh-group').on('click', function () {
                Controller.api.renderLayTree(true);
            })
            // 编辑按钮
            $('#toolbar').on('click', '.btn-edit', function (e) {
                var idx = $(this).attr('data-idx')
                if (!idx) {
                    Layer.msg('请选择组别后再进行编辑', {
                        icon: 2
                    });
                    return;
                }
                Mon.api.open(api.edit + '?idx=' + idx, '编辑角色组别', $(this).data() || {});
            })
            // 先隐藏编辑按钮，待选择组别后再渲染
            $('#toolbar .btn-edit, .btn-access, .btn-refresh').hide();
            // 绑定按钮
            $('#toolbar').on('click', '.btn-access', function (e) {
                var idx = $(this).attr('data-idx')
                if (!idx) {
                    Layer.msg('请选择组别后再进行关联', {
                        icon: 2
                    });
                    return;
                }
                var area = [$(window).width() > 560 ? '542px' : '90%', $(window).height() > 540 ? '500px' : '90%'];
                Mon.api.open(api.bindUser + '?idx=' + idx, '关联管理员用户', {
                    area: area
                });
            })
            // 初始化表格
            Controller.api.renderUserTable()
        },
        add: function () {
            Form.render()
            Form.submit('submit', function () {
                parent.$('#btn-refresh-group').trigger('click');
            })
        },
        edit: function () {
            // 渲染表单
            Form.render()
            // 扩展jstree, 读取选中的条目
            $.jstree.core.prototype.get_all_checked = function (full) {
                var obj = this.get_selected(),
                    i, j;
                for (i = 0, j = obj.length; i < j; i++) {
                    obj = obj.concat(this.get_node(obj[i]).parents);
                }
                obj = $.grep(obj, function (v, i, a) {
                    return v != '#';
                });
                obj = obj.filter(function (itm, i, a) {
                    return i == a.indexOf(itm);
                });
                return full ? $.map(obj, $.proxy(function (i) {
                    return this.get_node(i);
                }, this)) : obj;
            };

            Layui.use(['form'], function (form) {
                // 渲染节点
                Controller.api.queryRenderTree($("select[name='pid']").data("pid"));
                // 全选
                form.on('checkbox(checkall)', function (data) {
                    $("#treeview").jstree(data.elem.checked ? "check_all" : "uncheck_all");
                });
                // 展开
                form.on('checkbox(expandall)', function (data) {
                    $("#treeview").jstree(data.elem.checked ? "open_all" : "close_all");
                });
                // 变更父级后重新渲染节点树
                form.on('select(pid)', function (data) {
                    Controller.api.queryRenderTree(data.value)
                });
            })
            // 绑定表单提交
            Form.submit('submit', null, null, function (data) {
                if ($("#treeview").length > 0) {
                    var rules = $("#treeview").jstree("get_all_checked");
                    return {
                        rules: rules.join(',')
                    }
                }
            })
        },
        bindUser: function () {
            // 渲染穿梭框
            Layui.use(['transfer'], function (transfer) {
                transfer.render({
                    elem: '#transfer',
                    id: 'transfer',
                    title: ['用户列表', '已关联'],
                    showSearch: true,
                    searchPlaceholder: '用户名搜索',
                    data: window.transfer_data.users,
                    value: window.transfer_data.selects,
                    text: {
                        none: '无数据',
                        searchNone: '无匹配数据'
                    }
                })
                // 提交，获取右侧数据
                $('#transfer-submit').on('click', function () {
                    var data = transfer.getData('transfer'); //获取右侧数据
                    var uids = []
                    for (var i = 0, l = data.length; i < l; i++) {
                        var item = data[i]
                        uids.push(item['value'])
                    }
                    uids = uids.join(',')
                    Mon.api.ajax({
                        url: api.bindUser + '?idx=' + window.transfer_data.idx,
                        data: {
                            uids: uids
                        }
                    }, function (res, ret) {
                        //提示及关闭当前窗口
                        var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : '操作成功';
                        parent.Toastr.success(msg);
                        // 存在刷新按钮，且已绑定事件，则刷新上级table
                        parent.$(".btn-refresh").trigger("click");
                        var index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
                        return false;
                    })
                })
                // 重置
                $('#transfer-reset').on('click', function () {
                    transfer.reload('transfer', {
                        value: window.transfer_data.selects
                    });
                })
            })
        },
        api: {
            // 获取渲染树的数据
            queryRenderTree: function (pid) {
                var id = Mon.api.get('idx');
                $.ajax({
                    url: api.role,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        id: id,
                        pid: pid
                    },
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                            if (ret.code === 1) {
                                //销毁已有的节点树
                                $("#treeview").jstree("destroy");
                                Controller.api.rendertree(data);
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }
                    },
                    error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });
            },
            // 渲染数据
            rendertree: function (content) {
                $("#treeview")
                    .on('redraw.jstree', function (e) {
                        $(".layer-footer").attr("domrefresh", Math.random());
                    })
                    .jstree({
                        "themes": {
                            "stripes": true
                        },
                        "checkbox": {
                            "keep_selected_style": false,
                        },
                        "types": {
                            "root": {
                                "icon": "fa fa-folder-open",
                            },
                            "menu": {
                                "icon": "fa fa-folder-open",
                            },
                            "file": {
                                "icon": "fa fa-file-o",
                            }
                        },
                        "plugins": ["checkbox", "types"],
                        "core": {
                            'check_callback': true,
                            "data": content
                        }
                    });
            },
            // 渲染layui树
            renderLayTree: function (reload) {
                Layui.use('tree', function (tree) {
                    Mon.api.ajax({
                        type: 'get',
                        url: api.index
                    }, function (data) {
                        if (reload) {
                            tree.reload('groupTree', {
                                data: data
                            })
                        } else {
                            //渲染
                            tree.render({
                                id: 'groupTree',
                                elem: '#groupTree',
                                data: data,
                                onlyIconControl: true,
                                text: {
                                    defaultNodeName: '未命名',
                                    none: '无数据'
                                },
                                click: function (obj) {
                                    var field = obj.data
                                    // 渲染选择组别
                                    $('#selectGroupID').val(field.id)
                                    $('#selectGroup').html(field.title)
                                    $('#groupStatus').html(field.status == '1' ? '<apsn class="text-success">（有效）</span>' : '<apsn class="text-danger">（无效）</span>');
                                    // $('#toolbar .btn-access, .btn-refresh').show();
                                    // 判断可否编辑，进行渲染
                                    if (supper_group.indexOf(field.id) < 0) {
                                        $('#toolbar .btn-access, .btn-refresh, .btn-edit').attr('data-idx', field.id).show();
                                    } else {
                                        $('#toolbar .btn-refresh, .btn-access, .btn-edit').attr('data-idx', null).hide();
                                    }
                                    // 渲染角色组别用户
                                    Controller.api.renderUserTable(field.id, true);
                                }
                            });
                        }

                        return false
                    })
                });
            },
            renderUserTable: function (idx, reload) {
                var url = api.user + (idx ? '?gid=' + idx : '');
                if (reload) {
                    Table.reload('table', {
                        url: url,
                        page: {
                            curr: 1,
                        },
                    })
                } else {
                    // 渲染角色用户
                    Table.render({
                        elem: '#table',
                        url: url,
                        text: {
                            none: '无数据或请先选择组别',
                        },
                        cols: [[
                            { field: 'id', title: 'ID', width: 80, align: 'center' },
                            { field: 'username', title: '用户名', minWidth: 120 },
                            { field: 'avatar', title: '头像', width: 80, align: 'center', templet: function (d) { return Table.format.avatar(d.avatar) } },
                            { field: 'login_ip', title: '登录IP', width: 140, align: 'center' },
                            { field: 'login_time', title: '最后登录时间', width: 168, align: 'center', templet: function (d) { return d.login_time ? Table.format.dateTime(d.login_time) : ''; }, sort: true },
                            { field: 'status', title: '状态', width: 100, templet: function (d) { return Table.format.status(d.status) }, align: 'center' },
                            { field: 'operate', title: '操作', templet: '#operate', minWidth: 120 }
                        ]]
                    });
                    // 绑定表格事件
                    Table.bindEvent('table', api);
                    Table.callback(function (table) {
                        table.on('tool(table)', function (obj) {
                            var data = obj.data;
                            var event = obj.event;
                            if (event == 'unbind') {
                                Layer.confirm('确认移除该关联用户么？', {
                                    icon: 3,
                                    title: '提示'
                                }, function (index) {
                                    var query = {
                                        url: api.unbind,
                                        data: {
                                            uid: data.id,
                                            gid: $('#selectGroupID').val()
                                        }
                                    }
                                    // 发起请求
                                    Mon.api.ajax(query, function () {
                                        // 成功则刷新表格，
                                        Layer.close(index);
                                        Table.reload(Table.config.id)
                                    });
                                })
                            }
                        })

                    })
                }

            }
        }
    };
    return Controller;
});